package dao;

import domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import util.JDBCUtils;

@Repository
public class UserDao{
    //声明一个成员变量：JDBCTemplate对象共用
    //private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Autowired
    private JdbcTemplate template;

    /*
     *
     * 登录方法
     * @param loginUser 只有用户名和密码
     * @return user包含用户全部数据
     * */
    public User login(User loginUser){
        try {
            //编写sql
            String sql = "select * from user where username = ? and password = ?";

            //调用query方法
            User user = template.queryForObject(sql,
                    new BeanPropertyRowMapper<User>(User.class),
                    loginUser.getUsername(), loginUser.getPassword());
            return user;
        } catch (DataAccessException e) {
            e.printStackTrace();
            return null;
        }
    }

    public User findByUsername(String username){
        User user = null;
        try {
            //1.定义sql
            String sql = "select * from user where username = ?";

            //2.执行sql
            user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return user;
    }

    public void save(User user){
        //1.定义sql
        String sql = "insert into user(username,password) values(?,?)";
        //2.执行sql
        template.update(sql,user.getUsername(),user.getPassword());
    }

}
